<?php
namespace app\member\controller;
use think\Controller;
use think\Log;
class Member extends Controller{
    public function login() {
        if (request()->isPost()){
            $data = input();
            //判断手机号是否注册
            if (!isset_user($data['telphone'])){
                echo "{\"code\":1001,\"msg\":\"该手机号尚未注册！\"}";
                exit();
            }
            //校验用户账号密码
            $user = check_user($data['telphone'], $data['password']);
            if ($user===false){
                echo "{\"code\":1002,\"msg\":\"账号或密码错误！\"}";
                exit();
            }
            if ($user['status']==0||$user['status']==-1){
                die("{\"code\":1003,\"msg\":\"用户未审核或审核未通过！\"}");
            }
            //成功登陆
            setSession("user", $user);
            if ($user['role']==0){//学员
                die("{\"code\":0,\"msg\":\"学员登陆成功！\",\"url\":\"".url('member/student/index')."\"}");
            }else if ($user['role']==1){//教练
                die("{\"code\":0,\"msg\":\"教练登陆成功！\",\"url\":\"".url('member/coach/index')."\"}");
            }
            
            
            //判断用户是否审核通过
            exit();
        }
        return $this->fetch();
    }
    /**
     * 用户注册方法
     */
    public function register(){
        if (request()->isPost()){
           $data = input();
           //校验两次密码是否一致
           if ($data['password']!=$data['repassword']){
               echo "两次密码输入不一致！";
               exit();
           }else{
               $data['password'] = md5($data['password']);
               unset($data['repassword']);
           }
           //校验手机号是否存在
           if(isset_user($data['telphone'])){
               echo "该手机号已注册！";
               exit();
           }
           $data['create_time'] = time();
           $data['status']=0;
           
           try {
               $res = db("member")->insert($data);
               if ($res){
                   echo "注册成功，等待管理员审核！";
                   exit();
               }else{
                   echo "注册失败！";
                   exit();
               }
           } catch (\Exception $e) {
               //Log::write(json_encode($e));
               echo $e->getMessage();
               exit();
           }
           exit();
        }
        return $this->fetch();
    }
    
    public function logout(){
        setSession("user",null);
        return redirect(url("member/login"));
    }
}